﻿namespace com.crownpack.Extensions.SharePointExtensions
{
    using System;
    using System.Linq;

    using Microsoft.SharePoint;

    public static class SPFeatureCollectionExtensions
    {
        #region Methods

        public static void EnsureActivated( this SPFeatureCollection features, Guid featureId )
        {
            try
            {
                if ( !IsActivated( features, featureId ) )
                    features.Add( featureId );
            }
            catch
            {
                // throw away error condition; feature already activated
            }
        }

        public static void EnsureActivated( this SPFeatureCollection features, string featureId )
        {
            EnsureActivated( features, new Guid( featureId ) );
        }

        public static void EnsureDeactivated( this SPFeatureCollection features, Guid featureId )
        {
            if ( IsActivated( features, featureId ) )
                features.Remove( featureId );
        }

        public static void EnsureDeactivated( this SPFeatureCollection features, string featureId )
        {
            EnsureDeactivated( features, new Guid( featureId ) );
        }

        public static bool IsActivated( this SPFeatureCollection features, Guid featureId )
        {
            return features.Cast<SPFeature>( ).FirstOrDefault( f => f.DefinitionId.Equals( featureId ) ) != null;
        }

        public static bool IsActivated( this SPFeatureCollection features, string featureId )
        {
            return IsActivated( features, new Guid( featureId ) );
        }

        #endregion Methods
    }
}